import React, { Component, PropTypes } from 'react'
import { Form, Input, Button, Select, message, Icon, Row, Col } from 'antd'
import Style from '../Index.less'
import { fetchPost } from '../../../utils/request'
import { history } from '../../../utils/config'
import Title from '../../common/components/Title'

const FormItem = Form.Item
const Option = Select.Option

class Index extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      roles: [],
      data: {},
      isEdit: false,
      productList: [],
      sdzzProductListData: [],
      sdzzProductList: [],
      sdzzProductSelectState: 'none',
      sdzzProductRequireState: false,
      selectedRoles: []
    }
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  componentDidMount () {
    if (this.props.params.id) {
      console.log(this.props.location.state.data, 'this.props.location.state.data')
      let rolesS = this.props.location.state.data.roleIds
      let roles = trimSpace(rolesS)
      this.setState({
        data: this.props.location.state.data,
        isEdit: true,
        selectedRoles: roles
      }, () => {
        console.log(this.state.selectedRoles, '')
      })
    }

    function trimSpace (array) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] !== '' || typeof (array[i]) !== 'undefined') {
          array[i] = '' + array[i] + ''
        }
      }
      return array
    }

    this.getRoles()
    this.getProductType()
    this.getSdzzProductType()
  }

  getRoles () {
    fetchPost('/admin/role/list?currentPage=1&pageSize=500', {}).then(json => {
      let data = json.data.list
      this.setState({
        roles: data,
      })
    })
  }

  getProductType () {
    fetchPost('/admin/producttype/list', {}).then(res => {
      if (res.code === 0) {
        let list = res.data.list
        if (list.length) {
          list.unshift({
            code: 'all',
            name: 'All',
          })
          this.setState({
            productList: list
          })
        }
      }
    })
  }

  getSdzzProductType () {
    fetchPost('/admin/sdzzproduct/list', {}).then(res => {
      if (res.code === 0) {
        let list = res.data.list
        if (list.length) {
          this.setState({
            sdzzProductListData: list
          })
        }
      }
    })
  }

  getRoleOptions () {
    let roles = this.state.roles
    let options = []
    if (roles !== null) {
      roles.map(function (role) {
        options.push(
          <Option key={role.id}>
            {role.name}
          </Option>,
        )
      })
      return options
    }
  }

  handleChange (event) {
    // console.log('--handleChange--', event)
    let { sdzzProductList, sdzzProductListData, sdzzProductSelectState, sdzzProductRequireState } = this.state
    if (event === 'sdzzall' || event === 'sdzzold') {
      sdzzProductList = sdzzProductListData
      sdzzProductSelectState = ''
      sdzzProductRequireState = true
    } else {
      sdzzProductList = []
      sdzzProductSelectState = 'none'
      sdzzProductRequireState = false
    }
    this.setState({
      sdzzProductList,
      sdzzProductSelectState,
      sdzzProductRequireState,
    })
  }

  handleSubmit () {
    let self = this
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        const { name, productCode, mobilephone, fullName, roles, password } = this.props.form.getFieldsValue()
        let { productAuthId } = this.props.form.getFieldsValue()
        if (productCode === 'sdzzall' || productCode === 'sdzzold') {
          if (productAuthId === 'ALL') {
            productAuthId = 1
          }
        } else {
          productAuthId = ''
        }
        if (this.state.isEdit) {
          fetchPost(`/admin/${self.props.params.id}/update`, {
            name,
            productCode,
            mobilephone,
            fullName,
            roles,
            productAuthId,
            password,
          }).then(json => {
            if (json.code === 0) {
              message.success('Update Success')
              history.push('/admin/list')
            } else {
              message.error(json.msg)
            }
          })
        } else {
          // console.log('--111-1-', {name, productCode, mobilephone, fullName, roles, productAuthId});
          fetchPost('/admin/add', {
            name,
            productCode,
            mobilephone,
            fullName,
            roles,
            productAuthId,
            password,
          }).then(json => {
            if (json.code === 0) {
              message.success('Create Success')
              history.push('/admin/list')
            } else {
              message.error(json.msg)
            }
          })
        }
      }
    })
  }

  handleReset () {
    this.props.form.resetFields()
  }

  render () {
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    }
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <Title title={this.state.isEdit ? 'Edit' : 'New'}/>
        <div className={Style.editAdminWrapper}>
          <Form horizontal>
            <FormItem
              {...formItemLayout}
              label='Login account'
              hasFeedback
            >
              {getFieldDecorator('name', {
                initialValue: this.state.data.name || '',
                rules: [
                  { required: true, message: 'Name can not be empty!' },
                ],
              })(
                <Input/>,
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label='Last Name'
              hasFeedback
            >
              {getFieldDecorator('fullName', {
                initialValue: this.state.data.fullName || '',
                rules: [
                  { required: true, message: 'Name can not be Empty' },
                ],
              })(
                <Input/>,
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label='Phone Num'
              hasFeedback
            >
              {getFieldDecorator('mobilephone', {
                initialValue: this.state.data.mobilephone || '',
                rules: [
                  { required: true, message: 'Phone num can not be empty' },
                ],
              })(
                <Input/>,
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label='Password'
              hasFeedback
            >
              {getFieldDecorator('password', {
                initialValue: '',
                rules: [
                  {
                    required: true,
                    pattern: '^[0-9a-zA-Z_]{1,}$',
                    message: 'Must been digits and letters',
                  },
                ],
              })(
                <Input/>,
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label='Role Selector'
            >
              {getFieldDecorator('roles', {
                rules: [
                  { required: true, message: 'Choose Role', type: 'array', },
                ],
                initialValue: this.state.selectedRoles
              })(
                <Select multiple placeholder='Choole Role'>
                  {this.getRoleOptions()}
                </Select>,
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label='Product Type'
            >
              <Row gutter={8}>
                <Col span={12}>
                  {getFieldDecorator('productCode', {
                    initialValue: this.state.isEdit && this.state.data.productCode
                      ? this.state.data.productCode.toString()
                      : 'all',
                    rules: [
                      { required: true, message: 'Product Type can not be empty' },
                    ],
                  })(
                    <Select placeholder='Type' onChange={(e) => this.handleChange(e)}
                    >
                      {
                        this.state.productList.map((value, index) => (
                          <Option value={value.code} key={value.code}>{value.name}</Option>
                        ))
                      }
                    </Select>,
                  )}
                </Col>
                <Col span={12} style={{ 'display': this.state.sdzzProductSelectState }}>
                  {getFieldDecorator('productAuthId', {
                    initialValue: 1,
                    rules: [
                      { required: true, message: 'Product type detail can not be empty' },
                    ],
                  })(
                    <Select placeholder='type'
                    >
                      {
                        this.state.sdzzProductList.map((value, index) => (
                          <Option value={value.id} key={value.id}>{value.name}</Option>
                        ))
                      }
                    </Select>,
                  )}
                </Col>
              </Row>
            </FormItem>

            <FormItem wrapperCol={{ span: 12, offset: 6 }}>
              <Button type='primary' onClick={this.handleSubmit}
                      htmlType='submit'>
                {
                  this.state.isEdit ? 'Edit' : 'New'
                }
              </Button>
              &nbsp;
              <Button type='ghost' onClick={(e) => this.handleReset(e)}><Icon
                type='reload'/></Button>
            </FormItem>

          </Form>
        </div>
      </div>
    )
  }
}

Index = Form.create()(Index)
export default Index
